package com.focus.xyz.core.common.webdriver;

import com.focus.xyz.core.utils.prop.ConfigProp;
import com.focus.xyz.core.utils.prop.ConfigPropInfo;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerDriverService;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

import java.net.URL;
import java.util.Arrays;

/**
 * Created by chenmeng on 2016/4/19.
 */
public class RemoteDriver implements IDriver {
    private String nodeUrl;
    private WebDriver driver;
    private DesiredCapabilities capabilities;
    private SeleConst.DeviceEnum device;

    public RemoteDriver(String nodeUrl) {
        this.nodeUrl = nodeUrl;
    }


    public WebDriver getBrowser(String browser) throws Exception {
        switch (SeleConst.DriverEnum.getEnum(browser)) {
            case CHROME: {
                capabilities = DesiredCapabilities.chrome();
                ChromeOptions options = new ChromeOptions();
                options.setBinary(ConfigPropInfo.CHROME_BIN);
                options.addArguments("--test-type", "--start-maximized");
                options.addArguments("--test-type", "--ignore-certificate-errors");
                capabilities.setCapability("chrome.switches", Arrays.asList("--start-maximized"));
                capabilities.setCapability(ChromeOptions.CAPABILITY, options);
                break;
            }
            case IE:{
                capabilities = DesiredCapabilities.internetExplorer();
                capabilities.setBrowserName("internet explorer");
                capabilities.setPlatform(Platform.WINDOWS);
                capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
                break;
            }
            case FIREFOX:
            {
                capabilities = DesiredCapabilities.firefox();
                capabilities.setBrowserName("firefox");
                capabilities.setPlatform(Platform.ANY);
                break;
            }
            case SAFARI:
            {
                capabilities = DesiredCapabilities.safari();
                capabilities.setPlatform(Platform.MAC);
            }
            default:
            {
                throw new Exception("unsupported browser type");
            }
        }
        driver = new RemoteWebDriver(new URL(nodeUrl), capabilities);
        return driver;
    }

    public IDriver getDevice(String device) throws Exception {
        this.device = SeleConst.DeviceEnum.getDevice(device);
        return this;
    }
}
